#!bin/perl

## ----------------------------------------------------
## Title :			...
## Description :	...
## Date :			201x-xx-xx
## Version :		0.1
## Author :			@TiTom
## ----------------------------------------------------

## ----------------------------------------------------
## Todo List
## ----------------------------------------------------
## - ...
## ----------------------------------------------------


use strict;
use warnings;
use Date::Parse;
use Data::Dumper;

our $VERSION = 0.1;

##	Constants
use constant TRUE=> 1;
use constant FALSE=> 0;


my $lfile = '/var/lib/dhcp/dhcpd.leases';
my $sname = "as73.inetsix.net";

local *LF;
local $/ = "}\n";

my %ll;

return unless open(LF,$lfile);
#print STDERR "$0: ",(scalar localtime)," in make_lease_list, parsing $lfile\n";

while (<LF>) {
    next unless /^lease\s+(\S+)\s+/m;
    my $IP = $1;
    next if /binding state backup/;
    delete $ll{$IP} if exists $ll{$IP} && $ll{$IP}->{server} eq $sname;
    $ll{$IP}->{type}   = "dynamic";
    $ll{$IP}->{state}  = $1  if /binding state\s+([^\;]+)/;
    $ll{$IP}->{MAC}    = $1  if /hardware ethernet\s+([^\;]+)/;
    $ll{$IP}->{uid}    = $1  if /uid\s+([^\;]+)/;
    $ll{$IP}->{chname} = $1  if /client-hostname\s+([^\;]+)/;
    foreach my $time ( qw / starts ends / ) {
        if ( /$time\s+([^\;]+)/ ) {
        my $utm = substr($1,-19);
        $ll{$IP}->{time} = $utm;
        #$ll{$IP}->{time} = str2time($utm,"UTC");
        }
    }
    $ll{$IP}->{server} = $sname;
}
close LF;

print "---------------------------------------------------------\n";
print "Active leases :\n";
print "---------------------------------------------------------\n";
foreach my $lk ( sort keys %ll ) {
    #delete $ll{$lk}, next unless $ll{$lk}->{state} eq 'active';
	if( $ll{$lk}->{state} eq 'active' and defined $ll{$lk}->{chname})
	{
		print "  * $lk\t$ll{$lk}->{chname} [$ll{$lk}->{MAC}] is active since $ll{$lk}->{time}\n";
	}
	elsif ($ll{$lk}->{state} eq 'active')
	{
		 print "  * $lk\t[$ll{$lk}->{MAC}] is active since $ll{$lk}->{time}\n";
	}
}
print "\n";
print "---------------------------------------------------------\n";
print "Free leases :\n";
print "---------------------------------------------------------\n";
foreach my $lk ( sort keys %ll ) {
    #delete $ll{$lk}, next unless $ll{$lk}->{state} eq 'active';
	if( $ll{$lk}->{state} eq 'free' )
	{
		print "  * $lk\t| $ll{$lk}->{MAC} is free since $ll{$lk}->{time}\n";
	}
}

